package com.rabbitmq.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.demo.datasource.OrderSource;
import com.rabbitmq.demo.entity.Order;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author liansongye
 * @create 2020/12/27 9:01 下午
 */
@RestController
public class TtlController {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping("/pay/{orderId}/{userName}")
    public String pay(@PathVariable Long orderId, @PathVariable String userName) {
        Order order = new Order(orderId, userName, formatDate(new Date()));
        amqpTemplate.convertAndSend("ex.go", "go", JSONObject.toJSONString(order));
        return "订单待支付";
    }

    @RequestMapping("/get/{userName}")
    public String getOrders(@PathVariable String userName){
        List<Order> orders = OrderSource.getOrders(userName);
        return JSONObject.toJSONString(orders);
    }

    private String formatDate(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    @RequestMapping("/notgo")
    public String getAccumulatedTask() {
        String notGo = (String) amqpTemplate.receiveAndConvert("q.go.dlx");
        return notGo;
    }
}
